import React from 'react';
import { Document, Page, pdfjs } from 'react-pdf';

import { sans } from '@/shared/fonts';
import cn from 'classnames';
import { useWindowSize } from 'usehooks-ts';

import cs from './PDFViewer.module.scss';

import 'react-pdf/dist/Page/AnnotationLayer.css';

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;

type Props = {
  file: any;
  loading?: boolean;
};
export const PDFViewer = ({ file, loading }: Props) => {
  const memoizedFile = React.useMemo(() => file, [file]);
  const [numPages, setNumPages] = React.useState<number | null>(null);
  const [pageBlockPage, setPageBlockPage] = React.useState(1);
  const [loadingProgress, setLoadingProgress] = React.useState(0);
  const [renderSuccess, setRenderSuccess] = React.useState(false);
  const { width } = useWindowSize();
  const onPageLoadSuccess = ({ numPages }: { numPages: number }) => {
    // setLoading(false);
    setNumPages(numPages);
  };
  const onLoadProgress = ({ loaded, total }: { loaded: any; total: any }) => {
    const progress = (loaded / total) * 100;
    setLoadingProgress(progress);
  };
  const pageBlockRef = React.useRef<HTMLDivElement>(null);
  React.useEffect(() => {
    const handleScroll = () => {
      if (!pageBlockRef.current) {
        return;
      }
      const scrollPosition = window.scrollY || window.pageYOffset;
      const pageHeight = width > 768 ? 805 : 520;
      const currentPage = Math.floor(scrollPosition / pageHeight) + 1;
      setPageBlockPage(currentPage);
    };

    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [width]);

  return (
    <>
      <Document
        externalLinkTarget="_blank"
        file={memoizedFile}
        onLoadProgress={onLoadProgress}
        onLoadSuccess={({ numPages }: { numPages: number }) => {
          onPageLoadSuccess({ numPages });
          setRenderSuccess(true);
        }}
        renderMode="canvas"
      >
        {renderSuccess &&
          Array.from({ length: numPages || 0 }, (el, pageIndex) => (
            <Page
              className={cs.pdf}
              key={pageIndex}
              loading={<></>}
              pageIndex={pageIndex}
              pageNumber={pageIndex + 1}
              renderTextLayer={false}
              width={width > 768 ? 604 : width}
            />
          ))}
      </Document>
      {!loading && numPages && loadingProgress > 99 && loadingProgress !== 0 && memoizedFile && (
        <div className={cn(cs.pageBlock, sans.className)} ref={pageBlockRef}>
          {pageBlockPage} из {numPages}
        </div>
      )}
    </>
  );
};

export default React.memo(PDFViewer);
